package com.omega.framework.common.util;

import com.omega.framework.common.exception.BaseServiceException;
import com.omega.framework.common.exception.ServiceException;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;

/**
 * 抛出异常工具类
 *
 * @author Lv.
 * @date 2022/11/2 12:11
 */
public class ThrowUtil {

    private static final String LINE_BREAK = "\r\n";
    public static final int INT_ZERO = 0;

    /**
     * 抛出运行时异常
     *
     * @param baseServiceException 异常码
     * @param msgArgs              参数
     */
    public static void throwMsg(BaseServiceException baseServiceException, Object... msgArgs) {
        if (msgArgs != null && msgArgs.length > 0) {
            throw new ServiceException(baseServiceException.getCode(), String.format(baseServiceException.getMessage(), msgArgs));
        } else {
            throw new ServiceException(baseServiceException);
        }
    }

    /**
     * 获取异常详细信息，Exception 转 String
     *
     * @param e
     * @return
     */
    public static String getErrorInfoFromException(Exception e) {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        try {
            e.printStackTrace(pw);
        } finally {
            try {
                sw.close();
            } catch (IOException ex) {
            }
            pw.close();
        }
        return LINE_BREAK + sw.toString() + LINE_BREAK;
    }

    /**
     * 获取异常详细信息，Exception 转 String,最大1000字符串
     *
     * @param e
     * @return
     */
    public static String getExceptionMsg(Exception e) {
        return substring(getErrorInfoFromException(e), 1000);
    }

    /**
     * 截取字符串长度
     *
     * @param str
     * @return
     */
    public static String substring(String str, int number) {
        if (StringUtils.isNotEmpty(str) && str.length() > number) {
            str = str.substring(INT_ZERO, number);
        }
        return str;
    }
}
